springboot的功能逐渐强大,除了可以给图片加水印以外,还能给图片加上二维码,支持私人订制,哈哈哈哈,废话不多说,直接上代码
首先是引入依赖,gradle是引入下面这两个,maven引入自行搜索
1 2
| compile("com.google.zxing:core:3.4.0") compile("com.google.zxing:javase:3.4.0")
|
然后进入正文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| @PostMapping("/watermarkImages") public String watermarkImages() throws Exception { String srcImgPath = "F://bg1.png"; String fileNameType = srcImgPath.substring(srcImgPath.lastIndexOf("."), srcImgPath.length()); String tarImgPath = CustomConfig.diskLocation + System.currentTimeMillis() + fileNameType; addWaterMark(srcImgPath, tarImgPath); return "success"; }
public void addWaterMark(String bigImgPath, String outPathWithFileName) throws Exception { File srcImgFile = new File(bigImgPath); Image srcImg = ImageIO.read(srcImgFile); int srcImgWidth = srcImg.getWidth(null); int srcImgHeight = srcImg.getHeight(null); BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufImg.createGraphics(); g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null); String content = "时光蹉跎看淡岁月你我"; Image image = QRCodeUtil.createImages(content); g.drawImage(image, 500, 500, null); g.setColor(Color.WHITE); g.dispose(); FileOutputStream outImgStream = new FileOutputStream(outPathWithFileName); ImageIO.write(bufImg, "png", outImgStream); System.out.println("添加水印完成"); outImgStream.flush(); outImgStream.close(); }
public static BufferedImage createImages(String content) throws Exception { Hashtable hints = new Hashtable(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 192, 192, hints); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } return image; }
|